<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>库存调拨管理系统</title>
    <!-- 引入Element UI样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
        }
        .app-container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        }
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        .search-form {
            margin-bottom: 20px;
        }
        .action-buttons {
            margin-bottom: 20px;
        }
        .el-table {
            margin-bottom: 20px;
        }
    </style>
</head>
<body>
<div id="app" class="app-container">
    <div class="header">
        <h2>库存调拨管理系统</h2>
        <el-button
                type="primary"
                icon="el-icon-plus"
                size="medium"
                @click="handleAdd">
            新增调拨
        </el-button>
    </div>

    <!-- 搜索表单 -->
    <el-form :model="queryParams" class="search-form" size="small" inline>
        <el-form-item label="调拨ID">
            <el-input
                    v-model="queryParams.transferId"
                    placeholder="请输入调拨ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="源库存ID">
            <el-input
                    v-model="queryParams.sourceInventoryId"
                    placeholder="请输入源库存ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item label="目标库存ID">
            <el-input
                    v-model="queryParams.destinationInventoryId"
                    placeholder="请输入目标库存ID"
                    clearable>
            </el-input>
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="action-buttons">

        <el-button
                type="danger"
                icon="el-icon-delete"
                size="medium"
                :disabled="multiple"
                @click="handleDelete">
            删除
        </el-button>
    </div>

    <!-- 调拨列表表格 -->
    <el-table
            :data="transferList"
            style="width: 100%"
            v-loading="loading"
            border
            stripe
            @selection-change="handleSelectionChange">
        <el-table-column
                type="selection"
                width="55"
                align="center">
        </el-table-column>
        <el-table-column
                prop="transferId"
                label="调拨ID"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="sourceInventoryId"
                label="源库存ID"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="destinationInventoryId"
                label="目标库存ID"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                prop="quantity"
                label="调拨数量"
                width="120"
                align="center">
        </el-table-column>
        <el-table-column
                label="调拨日期"
                width="180"
                align="center">
            <template slot-scope="scope">
                {{ formatDate(scope.row.transferDate) }}
            </template>
        </el-table-column>
        <el-table-column
                label="操作"
                width="180"
                align="center"
                class-name="action-buttons">
            <template slot-scope="scope">
                <el-button
                        size="mini"
                        @click="handleUpdate(scope.row)">
                    编辑
                </el-button>
                <el-button
                        size="mini"
                        type="danger"
                        @click="handleDelete(scope.row)">
                    删除
                </el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="queryParams.pageNum"
            :page-sizes="[10, 20, 30, 50]"
            :page-size="queryParams.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!-- 调拨对话框（新增/编辑） -->
    <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            :close-on-click-modal="false">
        <el-form
                :model="form"
                :rules="rules"
                ref="form"
                label-width="100px">
            <el-form-item
                    label="源库存ID："
                    prop="sourceInventoryId">
                <el-input
                        v-model="form.sourceInventoryId"
                        placeholder="请输入源库存ID"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="目标库存ID："
                    prop="destinationInventoryId">
                <el-input
                        v-model="form.destinationInventoryId"
                        placeholder="请输入目标库存ID"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="调拨数量："
                    prop="quantity">
                <el-input
                        v-model="form.quantity"
                        placeholder="请输入调拨数量"
                        type="number"
                        clearable>
                </el-input>
            </el-form-item>
            <el-form-item
                    label="调拨日期："
                    prop="transferDate">
                <el-date-picker
                        v-model="form.transferDate"
                        type="date"
                        value-format="yyyy-MM-dd"
                        placeholder="请选择调拨日期">
                </el-date-picker>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancel">取 消</el-button>
            <el-button
                    type="primary"
                    @click="submitForm"
                    :loading="submitting">
                {{ form.transferId ? '保存' : '新增' }}
            </el-button>
        </div>
    </el-dialog>
</div>

<!-- 引入Vue和Element UI -->
<script src="https://unpkg.com/vue@2.6.14/dist/vue.js"></script>
<script src="https://unpkg.com/element-ui/lib/index.js"></script>
<script src="../../plugins/axios/axios.min.js"></script>
<script src="https://unpkg.com/dayjs@1.10.7/dayjs.min.js"></script>

<script>
    // API请求函数
    const api = {
        listTransfer(query) {
            return axios.get('/transfer/transfer/list', { params: query });
        },
        getTransfer(transferId) {
            return axios.get('/transfer/transfer/' + transferId);
        },
        addTransfer(data) {
            return axios.post('/transfer/transfer', data);
        },
        updateTransfer(data) {
            return axios.put('/transfer/transfer', data);
        },
        delTransfer(transferId) {
            return axios.delete('/transfer/transfer/' + transferId);
        }
    };

    new Vue({
        el: '#app',
        data() {
            return {
                loading: false,          // 表格加载状态
                submitting: false,       // 提交按钮加载状态
                open: false,             // 对话框显示状态
                title: '新增调拨',      // 对话框标题
                transferList: [],       // 调拨列表数据
                selectedRows: [],        // 选中的行数据
                single: true,            // 是否单选
                multiple: true,         // 是否多选
                total: 0,               // 总条数
                queryParams: {           // 查询参数
                    pageNum: 1,
                    pageSize: 10,
                    transferId: '',
                    sourceInventoryId: '',
                    destinationInventoryId: '',
                    quantity: '',
                    transferDate: ''
                },
                form: {
                    transferId: '',
                    sourceInventoryId: '',
                    destinationInventoryId: '',
                    quantity: '',
                    transferDate: ''
                },               // 表单数据
                rules: {                // 表单验证规则
                    sourceInventoryId: [
                        { required: true, message: '请输入源库存ID', trigger: 'blur' }
                    ],
                    destinationInventoryId: [
                        { required: true, message: '请输入目标库存ID', trigger: 'blur' }
                    ],
                    quantity: [
                        { required: true, message: '请输入调拨数量', trigger: 'blur' },
                        { pattern: /^[1-9]\d*$/, message: '请输入正整数', trigger: 'blur' }
                    ],
                    transferDate: [
                        { required: true, message: '请选择调拨日期', trigger: 'change' }
                    ]
                }
            };
        },
        created() {
            this.getList();
        },
        methods: {
            // 格式化日期显示
            formatDate(date) {
                if (!date) return '-';  // 如果日期为空，返回 -
                return dayjs(date).format('YYYY-MM-DD HH:mm:ss');  // 使用 dayjs 格式化日期
            },

            // 获取调拨列表
            getList() {
                this.loading = true;
                const params = {
                    pageNum: this.queryParams.pageNum,
                    pageSize: this.queryParams.pageSize,
                    transferId: this.queryParams.transferId || null,
                    sourceInventoryId: this.queryParams.sourceInventoryId || null,
                    destinationInventoryId: this.queryParams.destinationInventoryId || null,
                    quantity: this.queryParams.quantity || null,
                    transferDate: this.queryParams.transferDate || null
                };

                api.listTransfer(params)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            this.transferList = response.data.data.records || [];
                            this.total = response.data.data.total || 0;
                        } else {
                            this.transferList = [];
                            this.total = 0;
                            this.$message.error(response.data.msg || "获取数据失败");
                        }
                    })
                    .catch(error => {
                        console.error('获取调拨列表失败:', error);
                        this.$message.error('获取调拨列表失败: ' + (error.response?.data?.message || error.message));
                        this.transferList = [];
                        this.total = 0;
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 搜索按钮操作
            handleQuery() {
                this.queryParams.pageNum = 1;
                this.getList();
            },

            // 重置查询
            resetQuery() {
                this.queryParams = {
                    pageNum: 1,
                    pageSize: 10,
                    transferId: '',
                    sourceInventoryId: '',
                    destinationInventoryId: '',
                    quantity: '',
                    transferDate: ''
                };
                this.getList();
            },

            // 处理选中行变化
            handleSelectionChange(selection) {
                this.selectedRows = selection;
                this.single = selection.length !== 1;
                this.multiple = !selection.length;
            },

            // 新增按钮操作
            handleAdd() {
                this.resetForm("form");
                this.form = {};
                this.open = true;
                this.title = "新增调拨";
            },

            // 修改按钮操作
            handleUpdate(row) {
                this.resetForm("form");
                this.loading = true; // 添加加载状态

                const transferId = row.transferId || this.selectedRows[0]?.transferId;
                if (!transferId) {
                    this.$message.warning('请选择要编辑的记录');
                    this.loading = false;
                    return;
                }

                api.getTransfer(transferId)
                    .then(response => {
                        if (response.data && response.data.code === 200) {
                            // 自动映射数据到表单
                            const data = response.data.data;
                            this.form = {
                                transferId: data.transferId || '',
                                sourceInventoryId: data.sourceInventoryId?.toString() || '',
                                destinationInventoryId: data.destinationInventoryId?.toString() || '',
                                quantity: data.quantity?.toString() || '',
                                transferDate: data.transferDate || ''
                            };
                            this.open = true;
                            this.title = "修改调拨";
                        } else {
                            this.$message.error(response.data?.msg || "获取调拨信息失败");
                        }
                    })
                    .catch(error => {
                        console.error('获取调拨信息失败:', error);
                        this.$message.error('获取调拨信息失败: ' + (error.response?.data?.message || error.message));
                    })
                    .finally(() => {
                        this.loading = false;
                    });
            },

            // 重置表单方法 - 确保完全重置
            resetForm(refName) {
                if (this.$refs[refName]) {
                    this.$refs[refName].resetFields();
                }
                this.form = {
                    transferId: '',
                    sourceInventoryId: '',
                    destinationInventoryId: '',
                    quantity: '',
                    transferDate: ''
                };
            },

            // 取消按钮
            cancel() {
                this.open = false;
                this.resetForm("form");
            },

            // 提交表单
            submitForm() {
                this.$refs["form"].validate(valid => {
                    if (valid) {
                        this.submitting = true;
                        const operation = this.form.transferId
                            ? api.updateTransfer(this.form)
                            : api.addTransfer(this.form);

                        operation.then(response => {
                            this.$message.success("操作成功");
                            this.open = false;
                            this.getList();
                        })
                            .catch(error => {
                                this.$message.error("操作失败: " + (error.response?.data?.message || error.message));
                            })
                            .finally(() => {
                                this.submitting = false;
                            });
                    }
                });
            },

            // 删除按钮操作
            handleDelete(row) {
                const transferIds = row ? [row.transferId] : this.selectedRows.map(item => item.transferId);

                if (transferIds.length === 0) {
                    this.$message.warning('请至少选择一条记录');
                    return;
                }

                this.$confirm('确定要删除选中的调拨记录吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.loading = true;
                    api.delTransfer(transferIds.join(','))
                        .then(() => {
                            this.$message.success("删除成功");
                            this.getList();
                        })
                        .catch(error => {
                            this.$message.error("删除失败: " + (error.response?.data?.message || error.message));
                        })
                        .finally(() => {
                            this.loading = false;
                        });
                }).catch(() => {
                    // 用户取消删除
                });
            },

            // 分页大小改变
            handleSizeChange(val) {
                this.queryParams.pageSize = val;
                this.getList();
            },

            // 当前页改变
            handleCurrentChange(val) {
                this.queryParams.pageNum = val;
                this.getList();
            }
        }
    });
</script>
</body>
</html>